package rlink

import (
	"fmt"
	"gitee.com/ruige_fun/util/rpwd"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

// LinkMySQL 连接MySQL数据库，返回 *gorm.DB
func LinkMySQL(dbName string, logModel string, closeAffair bool, accPassword rpwd.AccountAndPassword) (*gorm.DB, error) {
	DSN := fmt.Sprintf(`%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local`,
		accPassword.Account, accPassword.Password, accPassword.IP, accPassword.Port, dbName)

	var lm logger.LogLevel
	switch logModel {
	case `Silent`:
		lm = logger.Silent
	case `Error`:
		lm = logger.Error
	case `Warn`:
		lm = logger.Warn
	case `Info`:
		lm = logger.Info
	default:
		lm = logger.Info
	}

	client, err := gorm.Open(mysql.Open(DSN), &gorm.Config{Logger: logger.Default.LogMode(lm), SkipDefaultTransaction: closeAffair})
	if err != nil {
		fmt.Println("连接 MySQL 数据库", dbName, "失败：", err)
		return nil, err
	}

	fmt.Println("连接 MySQL 数据库", dbName, "成功！")
	return client, nil
}
